package com.whitedust.ltzf.factory.defaults;

import com.whitedust.ltzf.factory.Configuration;
import com.whitedust.ltzf.factory.IPayFactory;
import com.whitedust.ltzf.payments.h5.H5PayApiService;
import com.whitedust.ltzf.payments.h5.IH5PayApi;
import com.whitedust.ltzf.payments.nativepay.INativePayApi;
import com.whitedust.ltzf.payments.nativepay.NativePayApiService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.jackson.JacksonConverterFactory;

import java.util.concurrent.TimeUnit;

/**
 * @author A
 * @since 2025/7/25 14:18
 */

@Data
@Slf4j
public class DefaultPayFactory implements IPayFactory {
    private final Configuration configuration;
    private final OkHttpClient httpClient;

    public DefaultPayFactory(Configuration configuration) {
        this.configuration = configuration;
        //1.日志配置
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
        httpLoggingInterceptor.setLevel(configuration.getLogLevel());
        //2.开启Http客户端
        this.httpClient = new OkHttpClient.Builder()
                .addInterceptor(httpLoggingInterceptor)
                .connectTimeout(configuration.getConnectionTimeout(), TimeUnit.SECONDS)
                .writeTimeout(configuration.getWriteTimeout(), TimeUnit.SECONDS)
                .readTimeout(configuration.getReadTimeout(), TimeUnit.SECONDS)
                .build();
    }

    @Override
    public NativePayApiService nativePayApiService() {
        //构建Api
        INativePayApi nativePayApi = new Retrofit.Builder()
                .baseUrl(configuration.getApiHost())
                .client(httpClient)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(JacksonConverterFactory.create())
                .build()
                .create(INativePayApi.class);
        //创建Native支付服务
        return new NativePayApiService(nativePayApi, configuration);
    }

    @Override
    public H5PayApiService h5PayApiService() {
        //构建Api
        IH5PayApi h5PayApi = new Retrofit.Builder()
                .baseUrl(configuration.getApiHost())
                .client(httpClient)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(JacksonConverterFactory.create())
                .build()
                .create(IH5PayApi.class);
        //创建Native支付服务
        return new H5PayApiService(h5PayApi, configuration);
    }
}
